import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import {
  clearHistoriesAction,
  clearSuggestsAction,
  getSuggestAction,
  setHistoriesAction,
} from '@/store/action/search';
import { setLocalHistories } from '@/utils/storage';
import { Toast } from 'antd-mobile';
import DOMPurify from 'dompurify';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import styles from './index.module.scss';

const highlight = (str: string, keyword: string) => {
  const reg = new RegExp(`(${keyword})`, 'gi');
  return str.replace(reg, '<span onclick="alert(123)">$1</span>');
};

export default function Search() {
  const dispatch = useDispatch();
  const histroy = useHistory();
  const { suggests, histories } = useAppSelector((state) => state.search);

  const [keyword, setKeyword] = useState('');
  const timerIdRef = useRef(-1);
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setKeyword(e.target.value.trim());

    clearTimeout(timerIdRef.current);
    timerIdRef.current = window.setTimeout(() => {
      if (!e.target.value) return;
      dispatch(getSuggestAction(e.target.value));
    }, 500);
  };

  const handleSearch = () => {
    if (!keyword) {
      Toast.show({ content: '搜索内容不能为空' });
      return;
    }

    histroy.push({
      pathname: '/search/result',
      search: `q=${keyword}`,
    });
    dispatch(setHistoriesAction(keyword));
  };

  useEffect(() => {
    setLocalHistories(histories);
  }, [histories]);

  useEffect(() => {
    if (!keyword) {
      dispatch(clearSuggestsAction());
    }
  }, [keyword, dispatch]);

  useEffect(() => {
    return () => {
      clearTimeout(timerIdRef.current);
      dispatch(clearSuggestsAction());
    };
  }, [dispatch]);

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  return (
    <div className={styles.root}>
      <NavBar
        right={
          <span className="search-text" onClick={handleSearch}>
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            <input
              type="text"
              placeholder="请输入关键字搜索"
              onChange={handleChange}
              value={keyword}
              onKeyDown={handleKeyDown}
            />

            <Icon type="iconbtn_tag_close" className="icon-close" onClick={() => setKeyword('')} />
          </div>
        </div>
      </NavBar>

      {!keyword ? (
        <div className="history" style={{ display: 'block' }}>
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={() => dispatch(clearHistoriesAction())}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {histories.map((item, index) => {
              return (
                <span className="history-item" key={index}>
                  {item}
                  <span className="divider"></span>
                </span>
              );
            })}
          </div>
        </div>
      ) : (
        <div className="search-result">
          {suggests.map((item, index) => {
            return (
              <div className="result-item" key={index}>
                <Icon className="icon-search" type="iconbtn_search" />

                <div
                  className="result-value"
                  dangerouslySetInnerHTML={{
                    __html: DOMPurify.sanitize(highlight(item, keyword)),
                  }}
                ></div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
